<script setup>
import { ref, onMounted } from "vue";
import {
  queryPageApi,
  saveApi,
  queryByIdApi,
  updateApi,
  deleteApi,
  queryAllDeptsApi,
  queryAllRolesApi,
} from "@/api/user";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit,
  UserFilled,
} from "@element-plus/icons-vue";

// 查询参数
const queryParams = ref({
  name: "",
  phone: "",
  deptId: "",
  status: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const userList = ref([]);
const deptList = ref([]);
const roleList = ref([]);
const total = ref(0);
const selectedRows = ref([]);

// 搜索
const search = async () => {
  const result = await queryPageApi(queryParams.value);
  if (result.code == 1) {
    userList.value = result.data.rows;
    total.value = result.data.total;
  }
};

// 清空
const clear = () => {
  queryParams.value.name = "";
  queryParams.value.phone = "";
  queryParams.value.deptId = "";
  queryParams.value.status = "";
  queryParams.value.page = 1;
  queryParams.value.pageSize = 10;
  search();
};

// 分页大小改变
const handleSizeChange = (val) => {
  search();
};

// 页码改变
const handleCurrentChange = (val) => {
  search();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 对话框相关
const dialogFormVisible = ref(false);
const formTitle = ref("");
const isEdit = ref(false);
const userFormRef = ref(null);

// 用户表单
const userForm = ref({
  username: "",
  password: "",
  name: "",
  phone: "",
  email: "",
  gender: "",
  status: "",
  deptId: "",
  roleId: "",
  image: "",
  remark: "",
});

// 表单校验规则
const rules = ref({
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度在2-20个字符之间", trigger: "blur" },
  ],
  name: [
    { required: true, message: "姓名不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在2-20个字符之间", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
    { min: 5, max: 50, message: "邮箱长度在5-50个字符之间", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
  remark: [{ max: 50, message: "备注长度不能超过50个字符", trigger: "blur" }],
});

// 添加用户
const handleAdd = () => {
  dialogFormVisible.value = true;
  formTitle.value = "新增用户";
  isEdit.value = false;
  userForm.value = {
    username: "",
    password: "",
    name: "",
    phone: "",
    email: "",
    gender: "",
    status: "",
    deptId: "",
    roleId: "",
    image: "",
    remark: "",
  };
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};

// 修改用户
const handleEdit = async (id) => {
  const result = await queryByIdApi(id);
  if (result.code == 1) {
    dialogFormVisible.value = true;
    formTitle.value = "修改用户";
    isEdit.value = true;
    userForm.value = result.data;
    if (userFormRef.value) {
      userFormRef.value.resetFields();
    }
  } else {
    ElMessage.error(result.msg);
  }
};

// 保存用户
const save = async () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      let result;
      if (isEdit.value) {
        result = await updateApi(userForm.value);
      } else {
        // 新增时设置默认密码
        userForm.value.password = userForm.value.username + "123";
        result = await saveApi(userForm.value);
      }
      if (result.code == 1) {
        ElMessage.success(isEdit.value ? "修改成功" : "添加成功");
        dialogFormVisible.value = false;
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      ElMessage.error("请按照提示进行操作");
    }
  });
};

// 删除用户
const handleDelete = async (id) => {
  ElMessageBox.confirm("您确认要删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const result = await deleteApi(id);
      if (result.code == 1) {
        ElMessage.success("删除成功");
        search();
      } else {
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的用户");
    return;
  }
  const ids = selectedRows.value.map((row) => row.id).join(",");
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个用户吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      const result = await deleteApi(ids);
      if (result.code == 1) {
        ElMessage.success("批量删除成功");
        search();
      } else {
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 头像上传相关
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传头像图片只能是 PNG/JPG/JPEG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

const customUpload = async (options) => {
  try {
    // 创建FormData对象
    const formData = new FormData();
    formData.append("image", options.file);

    console.log("开始上传文件:", options.file.name);

    // 使用request实例进行文件上传，保持与其他API一致的配置
    const result = await request.post("/upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    console.log("上传响应:", result);

    if (result.code === 1) {
      const fileUrl = result.data;
      userForm.value.image = fileUrl;
      options.onSuccess({ url: fileUrl });
      ElMessage.success("头像上传成功");
    } else {
      options.onError(new Error(result.msg || "上传失败"));
      ElMessage.error(result.msg || "上传失败");
    }
  } catch (error) {
    console.error("文件上传错误:", error);
    options.onError(error);
    ElMessage.error(`文件上传失败: ${error.message}`);
  }
};

// 获取部门列表
const getDeptList = async () => {
  const result = await queryAllDeptsApi();
  if (result.code == 1) {
    deptList.value = result.data;
  }
};

// 获取角色列表
const getRoleList = async () => {
  const result = await queryAllRolesApi();
  if (result.code == 1) {
    roleList.value = result.data;
  }
};

onMounted(() => {
  getDeptList();
  getRoleList();
  search();
});
</script>

<template>
  <div class="user">
    <!-- 搜索区域 -->
    <el-form
      :inline="true"
      :model="queryParams"
      ref="queryForm"
      class="search-form"
    >
      <el-form-item label="姓名">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="部门">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dept in deptList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search"
          ><el-icon><Search /></el-icon>搜索</el-button
        >
        <el-button @click="clear"
          ><el-icon><Refresh /></el-icon>清空</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd"
        ><el-icon><Plus /></el-icon>添加用户</el-button
      >
      <el-button type="danger" @click="handleBatchDelete"
        ><el-icon><Delete /></el-icon>批量删除</el-button
      >
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="userList"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="name" label="姓名" width="120" align="center" />
      <el-table-column
        prop="username"
        label="用户名"
        width="150"
        align="center"
      />
      <el-table-column label="头像" width="100" align="center">
        <template #default="scope">
          <el-avatar :size="40" :src="scope.row.image" :icon="UserFilled" />
        </template>
      </el-table-column>
      <el-table-column
        prop="deptName"
        label="部门"
        width="150"
        align="center"
      />
      <el-table-column
        prop="roleName"
        label="角色"
        width="150"
        align="center"
      />
      <el-table-column prop="phone" label="手机号" width="150" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status === 0" type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        width="180"
        align="center"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row.id)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/修改用户弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="formTitle" width="800px">
      <el-form
        :model="userForm"
        :rules="rules"
        ref="userFormRef"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
                placeholder="请输入用户名"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="userForm.gender"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="userForm.status"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="userForm.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select
                v-model="userForm.roleId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="customUpload"
            accept=".png,.jpg,.jpeg"
          >
            <img v-if="userForm.image" :src="userForm.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            图片上传,支持扩展名: .png/.jpg/.jpeg<br />
            大小限制: 2M
          </div>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入用户的备注信息,最多50字"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px; /* 添加圆角 */
}

.operation-area {
  margin: 20px 0;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  min-width: 200px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.divider {
  height: 0.5px;
  background-color: #dcdfe6;
  margin: 10px 0;
  width: 100%;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.upload-tip {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
  line-height: 1.5;
}

.dialog-footer {
  text-align: right;
}
</style>
